<?php
$fromRegister = isset($fromRegister) && $fromRegister;
if (!$fromRegister)
    require_once ('..' . DIRECTORY_SEPARATOR . 'initialize.php');
//GET Request
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
    include_once(Utils::getPath(array('shared', 'template.php')));
    include_once(Utils::getPath(array('repositories', 'userRepository.php')));

    if ($fromRegister) {
        $template = new Template('main');
    } else {
        $template = new Template('application');
        $userRepository = new UserRepository();
        $user = $userRepository->getById($_SESSION['authenticatedId']);
    }
    $template->initialize();

    if (isset($_SESSION['actualeditinguser'])) {
        $user = unserialize($_SESSION['actualeditinguser']);
        $user->setId($_SESSION['authenticatedId']);
        unset($_SESSION['actualeditinguser']);
    }

    //Clean the image if the user exit from the edit/register page
    $referer = basename(getenv("HTTP_REFERER"));
    if ($referer != 'edit.php' && $referer != 'register.php') {
        unset($_SESSION['previewsrc']);
    }

    //Clean temp files
    Utils::delete_files(Utils::getPath(array('uploads', 'temp')), '01:00:00');

    if (isset($_SESSION['previewsrc'])) {
        $previewsrc = $_SESSION['previewsrc'];
    } else {
        $previewsrc = $user->getImage();
    }
    ?>
    <script type="text/javascript" src="<?php echo Utils::getUrl('scripts/jquery.form.js') ?>"></script>
    <script type="text/javascript" src="<?php echo Utils::getUrl('scripts/edit.js') ?>"></script>
    
    <h2><?php echo $fromRegister ? 'Register' : 'Edit yout profile' ?></h2>

    <form id="form-edit" action="<?php echo $fromRegister ? 'register.php' : 'edit.php' ?>" method="post" enctype="multipart/form-data" onsubmit="return validateRegisterForm(this);">
        <div>
            <input type="hidden" id="edit-id" name ="id" value="<?php echo $user->getId(); ?>" />
            <?php if (!$fromRegister) { ?>
                <input type="hidden" id="edit-oldemail" name ="oldemail" value="<?php echo $user->getEmail(); ?>" />
            <?php } ?>
        </div>
        <div class="form-element">
            <label for="edit-username">Username</label>
            <?php if ($fromRegister) { ?>
                <input type="text" id="edit-username" name="username" value="<?php echo $user->getUserName() ?>" maxlength="32" onfocus="fieldHighlight(this, false)" />
            <?php } else { ?>
                <input type="text" id="edit-username" name="username" value="<?php echo $user->getUserName() ?>" maxlength="32" onfocus="fieldHighlight(this, false)" readonly="readonly" />
            <?php } ?>
        </div>

        <div class="form-element">
            <label for="edit-password"><?php echo $fromRegister ? 'Password' : 'Old password (only if you want to change it)' ?></label>
            <input type="password" id="edit-password" name="password" maxlength="32" onfocus="fieldHighlight(this, false)" />
        </div>
        <?php if (!$fromRegister) { ?>
            <div class="form-element">
                <label for="edit-newpassword">New password</label>
                <input type="password" id="edit-newpassword" name="newpassword" maxlength="32" onfocus="fieldHighlight(this, false)" />
            </div> 
        <?php } ?>
        <div class="form-element">
            <label for="edit-repassword">Repeat password</label>
            <input type="password" id="edit-repassword" name="repassword" maxlength="32" onfocus="fieldHighlight(this, false)" />
        </div>

        <div class="form-element">
            <label for="edit-name">Name</label>
            <input type="text" id="edit-name" name="name" value="<?php echo $user->getName() ?>" maxlength="64" onfocus="fieldHighlight(this, false)" />
        </div>

        <div class="form-element">
            <label for="edit-email">Email</label>
            <input type="text" id="edit-email" name="email" value="<?php echo $user->getEmail() ?>" maxlength="64" onfocus="fieldHighlight(this, false)" />
        </div>

        <div class="form-element">
            <label for="edit-reemail">Repeat email</label>
            <input type="text" id="edit-reemail" name="reemail" maxlength="64" onfocus="fieldHighlight(this, false)" />
        </div>

        <div class="form-element">
            <label for="preview">Avatar</label>
            <img alt="<?php echo isset($previewsrc) ? 'User avatar' : 'No avatar' ?>" src="<?php
        if (isset($previewsrc)) {
            echo Utils::getUrl($previewsrc);
        } else {
            echo Utils::getUrl('uploads/default.png');
        }
        ?>" id="preview"/>

            <input type="file" accept='image/jpg'  id="edit-image" name="image" onchange="loadImage()" />
        </div>

        <div class="form-element">
            <label for="edit-description">Description</label>
            <textarea name="description" id="edit-description" onkeypress="return imposeMaxLength(this, 512);" rows="8" cols="64" ><?php echo $user->getDescription() ?></textarea>
        </div>

        <div class="submit">
            <input type="submit" value="Submit"/>
        </div>

    </form>
    <?php
    if ($fromRegister)
        $template->createPage('Register Page');
    else
        $template->createPage('Edit your profile');
}
//POST Request
else if ($_SERVER['REQUEST_METHOD'] == 'POST' && !isset($_REQUEST['preview'])) {
    include_once(Utils::getPath(array('repositories', 'userRepository.php')));
    $userRepository = new UserRepository();

    $errorList = array();
    $errorredirect = $fromRegister ? 'register.php' : 'edit.php';


    if (count($_REQUEST) > 0) {
        if (!$fromRegister) {
            $userOld = $userRepository->getById($_SESSION['authenticatedId']);
        }

        $user = new User();
        $user->setDescription(htmlentities($_REQUEST['description']));
        $user->setEmail(htmlentities($_REQUEST['email']));
        $user->setName(htmlentities($_REQUEST['name']));
        $user->changePassword($_REQUEST['password']); //this encode md5 password
        $user->setUserName($_REQUEST['username']);
        $_SESSION['actualeditinguser'] = serialize($user);

        //Data check
        $repassword = $_REQUEST['repassword'];
        $reemail = htmlentities($_REQUEST['reemail']);
        $previewsrc = isset($_SESSION['previewsrc']) ? $_SESSION['previewsrc'] : null;
    } else {
        $errorList[] = "Submit incorrect. Try again.";
    }

    //Check image properties
    if ((!empty($_FILES["image"])) && ($_FILES['image']['error'] == 0)) {
        $name_file = $_FILES['image']['name'];
        $type_file = $_FILES['image']['type'];
        $size_file = $_FILES['image']['size']; //bytes
        $max_size = 1; //MB

        if ($type_file != "image/gif" && $type_file != "image/jpeg" && $type_file != "image/png" && $type_file != "image/bmp") {
            $errorList[] = "Only jpeg, gif, bmp and png images are accepted for upload";
        }
        if ($size_file > ($max_size * 1048576)) {//1048576 = 1024 * 1024
            $errorList[] = "Images must be under $max_size MB in size";
        }
    }
    //Check for errors
    if ($errorList) {
        Utils::showErrorList($errorList);
        header("Location: $errorredirect");
        exit();
    }

    //Editing validation
    if (!$fromRegister) {
        if ($_REQUEST['password'] != '') {
            if ($user->validateEncodedPassword($userOld->getPassword())) {
                //ValidatePassword
                $validatePassword = true;
                $user->changePassword($_REQUEST['newpassword']);
            } else {
                $errorList[] = 'Old password not valid';
            }
        } else if ($_REQUEST['newpassword'] != '') {
            $errorList[] = 'Old password not valid';
        }

        if ($reemail != '' || $user->getEmail() != $userOld->getEmail()) {
            //ValidateEmail
            $validateEmail = true;
        }
    }


    //Register Validation
    if ($fromRegister) {
        if ($user->getUserName() == '') {
            $errorList[] = 'Empty username';
        } else {
            //Search user in database
            $userRep = new UserRepository();
            $userByName = $userRep->findByUserName($user->getUserName());
            if (!is_null($userByName)) {
                $errorList[] = 'The specified username is already in use';
                $regform['username'] = '';
            }
            $userByName = $userRep->find(array(array('Email = ?', $user->getEmail(), PDO::PARAM_STR)));
            if (!empty($userByName)) {
                $errorList[] = 'The specified email is already in use';
                $regform['email'] = '';
                $regform['reemail'] = '';
            }
        }
    }
    if ($fromRegister || (isset($validatePassword) && $validatePassword)) {
        $password = $fromRegister ? $_REQUEST['password'] : $_REQUEST['newpassword'];

        if ($user->validatePassword('')) {
            if ($fromRegister)
                $errorList[] = 'Empty password';
            else
                $errorList[] = 'Empty new password';
        } else if (preg_match($expPass, $password) == 0) {
            if ($fromRegister)
                $errorList[] = 'Password is not safe enough. Length must be between 6 and 12 characters and at least one digit and one alfanumeric character are necessary. Special caracters are not allowed';
            else
                $errorList[] = 'New password is not safe enough. Length must be between 6 and 12 characters and at least one digit and one alfanumeric character are necessary. Special caracters are not allowed';
        } else if ($user->getPassword() != $user->validatePassword($repassword)) {
            $errorList[] = 'Password and repeated password have differences, please repeat again';
        }
    }

    if ($fromRegister || (isset($validateEmail) && $validateEmail)) {
        if ($user->getEmail() == '') {
            $errorList[] = 'Empty email';
        } else if (preg_match($expEmail, $user->getEmail()) == 0) {
            $errorList[] = 'Email is incorrect';
            $regform['email'] = '';
            $regform['reemail'] = '';
        } else if ($user->getEmail() != $reemail) {
            $errorList[] = 'Email and repeated email have differences, please repeat again';
            $regform['reemail'] = '';
        }
    }

    if ($user->getName() == '') {
        $errorList[] = 'Empty name';
    }
    if (strlen($user->getDescription()) > 512) {
        $errorList[] = 'The maximum size of the description is 512 characters';
    }
    //Check for errors
    if ($errorList) {
        Utils::showErrorList($errorList);
        header("Location: $errorredirect");
        exit();
    }

    if (!$fromRegister) {
        $userOld->setDescription($user->getDescription());
        $userOld->setName($user->getName());
        if (isset($validateEmail) && $validateEmail) {
            $userOld->setEmail($user->getEmail());
        }
        if (isset($validatePassword) && $validatePassword) {
            $userOld->setPassword($user->getPassword());
        }
        $user = $userOld;
    }

    //Everything is ok, so we can update database
    //Update database
    $userRep = new UserRepository();

    //for get an id, persist the new user
    if ($fromRegister)
        $user = $userRep->persist($user);

    //Rename and move the last preview
    $src = '';
    if (isset($previewsrc)) {
        $type_file = $previewsrc;
        $type_file = strrchr($type_file, '.');
        $type_file = substr($type_file, 1, strlen($type_file));
        $src = 'uploads/' . $user->getId() . '.png';
        $from = Utils::getPath($previewsrc);
        $to = Utils::getPath(array('uploads', $user->getId() . '.' . $type_file));

        if (file_exists($to))
            unlink($to);

        if (!rename($from, $to)) {
            $imageerror = true;
        }
    } else if (isset($_FILES["image"]) && !empty($_FILES['image']['name'])) {
        //if image isn't upload by ajax
        $type_file = $_FILES['image']['type'];
        $type_file = strrchr($type_file, '/');
        $type_file = substr($type_file, 1, strlen($type_file));
        $src = 'uploads/' . $user->getId() . '.png';
        $path = Utils::getPath(array('uploads', $user->getId() . '.' . $type_file));
        if (move_uploaded_file($_FILES['image']['tmp_name'], $path)) {
            //Scale the image if it is greater than the width set above
            $result = Utils::resizeImage($path, 128);
            if (isset($result)) {
                $imageerror = true;
            } else {
                $_SESSION['previewsrc'] = $src;
            }
        } else {
            $imageerror = true;
        }
    }

    if (isset($imageerror) && $imageerror) {
        //if is a new user remove it, else not remove
        if ($fromRegister)
            $userRep->removeReal($user);

        Utils::showError('An error occurred uploading your image, please try again in a moment.');
        header("Location: $errorredirect");
        exit();
    }

    //only if image is set
    if (isset($src) && $src != '') {
        $user->setImage($src);
        $_SESSION['nocache'] = time();
    }

    $user = $userRep->persist($user);

    unset($_SESSION['actualeditinguser']);
    unset($_SESSION['previewsrc']);

    Utils::showInfo('Success!');
    header("Location: " . Utils::getUrl('/'));
    exit();
} else if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_REQUEST['preview']) && $_REQUEST['preview'] == '1') {

    ob_end_clean();
    //Check image properties
    $data = array("image" => null);
    $error = false;
    if ((!empty($_FILES["image"])) && ($_FILES['image']['error'] == 0)) {
        $name_file = $_FILES['image']['name'];
        $type_file = $_FILES['image']['type'];
        $size_file = $_FILES['image']['size']; //bytes
        $max_size = 1; //MB

        if ($type_file != "image/gif" && $type_file != "image/jpeg" && $type_file != "image/png" && $type_file != "image/bmp") {
            $data = array("image" => null);
            $error = true;
        }
        if ($size_file > ($max_size * 1048576)) {//1048576 = 1024 * 1024
            $data = array("image" => null);
            $error = true;
        }

        //Remove last preview
        if (isset($_SESSION['previewsrc']) && file_exists($_SESSION['previewsrc'])) {
            unlink($_SESSION['previewsrc']);
        }

        $type_file = $_FILES['image']['type'];
        $type_file = strrchr($type_file, '/');
        $type_file = substr($type_file, 1, strlen($type_file));

        $src = 'uploads/temp/' . strtotime(date('Y-m-d H:i:s')) . ".png";
        $path = Utils::getPath('uploads/temp/' . strtotime(date('Y-m-d H:i:s')) . ".$type_file");
        if (!$error && move_uploaded_file($_FILES['image']['tmp_name'], $path)) {

            //Scale the image if it is greater than the width set above
            $result = Utils::resizeImage($path, 128);
            if (isset($result))
            {
                $data = array("image" => null);   
            }
            else {
                $data = array("image" => Utils::getUrl($src));
                $_SESSION['previewsrc'] = $src;
            }
        } else {
            $data = array("image" => null);
        }
    }
    echo json_encode($data);
    exit();
}
?>
